"nodejs";
const koa = require("koa");
const app = new koa();
const { koaBody } = require("koa-body");
const router = require("koa-router")();
const fs = require("fs");

let dirName = "upload";
fs.mkdir(dirName, (err) => {
  // if (err) throw err; // 如果出现错误就抛出错误信息
  console.log("文件夹创建成功");
});

app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
    },
  })
);
router.get("/hello", async (ctx) => {
  console.log("hello");
  ctx.body = "router: hello world";
});
router.post("/upload", async (ctx) => {
  const file = ctx.request.files.file; // 获取上传文件
  const fileName = file.originalFilename;
  const reader = fs.createReadStream(file.filepath); // 创建可读流
  console.log(file.filepath);
  const writeStream = fs.createWriteStream(`${dirName}/${fileName}`); // 创建可写流
  reader.pipe(writeStream); // 可读流通过管道写入可写流
  console.log("文件写入完成");

  //文件关闭事件
  writeStream.on("close", () => {
    console.log("文件已关闭！");
    fs.unlink(file.filepath, (err) => {
      if (err) throw err;
      console.log("删除成功");
    });
  });

  return (ctx.body = "上传成功");
});
router.post("/download", async (ctx) => {
  const fileName = ctx.request.body.fileName; // build.zip
  const filePath =__dirname+`/${fileName}`;
  console.log(filePath);
  const stats = fs.statSync(filePath);
  if (stats.isFile()) {
    ctx.set("Content-Type", "application/octet-stream");
    ctx.set("Content-Disposition", "attachment; filename=" + fileName);
    ctx.set("Content-Length", stats.size);
    ctx.body = fs.createReadStream(filePath); // 创建可读流
  } else {
    ctx.body = { code: 500, message: "文件不存在" };
  }
});

// 调用router.routes()来组装匹配好的路由，返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件，当发送了不符合的请求时，会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
app.use(router.routes());
app.use(router.allowedMethods({}));
app.listen(3001, () => {
  console.log("koa is listening in 3001");
});
